#include "HttpServer.hpp"
#include <memory>
#include <fstream>

#define ROOT "./www"
#define HOMEPAGE "/index.html"

void service(int sockId)
{
    char inbuffer[10240];
    ssize_t s = recv(sockId, inbuffer, sizeof(inbuffer) - 1, 0);
    if (s > 0)
    {
        inbuffer[s] = 0;
        std::cout << inbuffer << std::endl;

        // 构建文件路径
        std::string file_path = ROOT;
        file_path += HOMEPAGE;

        // 打开文件
        std::ifstream file(file_path, std::ios::binary);
        std::string content;
        if (file.is_open())
        {
            std::string line;
            while (std::getline(file, line))
            {
                content += line + "\n"; // 添加换行符
            }
            file.close();
        }

        std::string HttpResponse;
        if (content.empty())
        {
            HttpResponse = "HTTP/1.1 404 Not Found\r\n";
            HttpResponse += "Content-Type: text/plain\r\n";
            HttpResponse += "\r\n";
            HttpResponse += "404 Not Found";
        }
        else
        {
            HttpResponse = "HTTP/1.1 200 OK\r\n";
            HttpResponse += "Content-Type: text/html\r\n";
            HttpResponse += "Content-Length: " + std::to_string(content.size()) + "\r\n";
            HttpResponse += "\r\n";
            HttpResponse += content;
        }

        send(sockId, HttpResponse.c_str(), HttpResponse.size(), 0);
    }
    close(sockId);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        exit(1);
    }

    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1])));

    httpserver->BindService(service);
    httpserver->Start();

    return 0;
}